import React from 'react';
import type { ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { getAdminGroupList, delAdminGroupById } from '@/services/system/admin';
import { Button, message, Popconfirm } from 'antd';
import AdminGroupEdit from './AdminGroupEdit';
import type { ActionType } from '@ant-design/pro-table/lib/typing';

export default () => {
  const [editVisible, setEditVisible] = React.useState(false);
  const [editAdminGroupId, setEditAdminGroupId] = React.useState(0);
  const tableRef = React.useRef<ActionType>();
  // 刷新List
  const listReload = () => {
    tableRef.current?.reload();
  };

  const columns: ProColumns<API.AdminGroup>[] = [
    {
      title: '权限组名称',
      dataIndex: 'groupName',
    },
    {
      title: '最后修改时间',
      dataIndex: 'gmtModified',
      valueType: 'dateTime',
    },
    {
      title: '操作',
      valueType: 'option',
      render: (_, entity) => [
        <a
          key="editable"
          onClick={() => {
            setEditAdminGroupId(entity.groupId);
            setEditVisible(true);
          }}
        >
          编辑
        </a>,
        <Popconfirm
          key="popconfirm"
          title="确定要删除吗？"
          onConfirm={() => {
            delAdminGroupById(entity.groupId).then((ren) => {
              if (ren.success) {
                message.success('删除成功');
                listReload();
              }
            });
          }}
        >
          <a key="delete">删除</a>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <>
      <ProTable<API.AdminGroup>
        actionRef={tableRef}
        columns={columns}
        rowKey="groupId"
        headerTitle="权限组列表"
        search={false}
        toolBarRender={() => [
          <Button
            type="primary"
            onClick={() => {
              setEditAdminGroupId(0);
              setEditVisible(true);
            }}
          >
            新建
          </Button>,
        ]}
        request={async () => {
          const result = await getAdminGroupList();
          return {
            data: result.data,
            success: result.success,
          };
        }}
      />

      {editVisible && (
        <AdminGroupEdit
          visible={editVisible}
          id={editAdminGroupId}
          setVisible={setEditVisible}
          listReload={listReload}
        />
      )}
    </>
  );
};
